package com.zanfeng.signleplatform.config.advices;

import com.zanfeng.signleplatform.api.exception.AppRuntimeException;
import com.zanfeng.signleplatform.api.exception.UnAuthorizedException;
import com.zanfeng.signleplatform.constants.Constants;
import com.zanfeng.signleplatform.results.ApiResult;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by Administrator on 2017/3/14 0014.
 * 控制器扩展处理
 */
@RestControllerAdvice("com.zanfeng.signleplatform")
public class WtControllerAdviceConfiguration {

    @ExceptionHandler(value = Exception.class)
    public ApiResult handleException(HttpServletRequest request, HttpServletResponse response, Exception exception) {
        if (exception instanceof AppRuntimeException) {
            //  业务异常
            return ApiResult.fail(exception.getLocalizedMessage());
        } else if (exception instanceof MethodArgumentNotValidException) {
            //  Hibernate Validator 异常(入参校验异常)
            List<ObjectError> objectErrorList = ((MethodArgumentNotValidException) exception).getBindingResult().getAllErrors();
            if (CollectionUtils.isNotEmpty(objectErrorList)) {
                return ApiResult.fail(objectErrorList.get(0).getDefaultMessage());
            }
        } else if (exception instanceof RuntimeException) {
            //  系统异常
//            return ApiResult.fail("发生错误，请联系管理员或稍候再试");
        }
        exception.printStackTrace();
        return ApiResult.fail("发生错误，请联系管理员或稍候再试");
    }

    @ExceptionHandler(value = UnAuthorizedException.class)
    public ApiResult handleUnAuthorizedException(HttpServletRequest request, HttpServletResponse response, Exception exception) {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", Constants.kAuth_xAccessToken);
        response.addHeader("Access-Control-Max-Age", "3600");
        return ApiResult.fail(Constants.kCode_UnAuth, "用户登录过期");
    }


}
